package com.tiantian.judge.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tiantian.api.RemoteUserService;
import com.tiantian.api.RemoteUserSolveService;
import com.tiantian.api.domain.vo.RemoteUserSolveVo;
import com.tiantian.api.domain.vo.RemoteUserVo;
import com.tiantian.common.core.constant.JudgeConstants;
import com.tiantian.common.core.exception.BusinessException;
import com.tiantian.judge.domain.entity.Judger;
import com.tiantian.judge.domain.entity.Judger2Answerer;
import com.tiantian.judge.domain.vo.JudgerVo;
import com.tiantian.judge.domain.vo.StaffVo;
import com.tiantian.judge.mapper.Judger2AnswererMapper;
import com.tiantian.judge.mapper.JudgerMapper;
import com.tiantian.judge.service.JudgerService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author tiantian
 */
@Service
@RequiredArgsConstructor
public class JudgerServiceImpl implements JudgerService {

    private final JudgerMapper judgerMapper;
    private final Judger2AnswererMapper judger2AnswererMapper;
    @DubboReference
    private RemoteUserService remoteUserService;
    @DubboReference
    private RemoteUserSolveService remoteUserSolveService;

    @Override
    public List<StaffVo> getStaffs() {
        List<RemoteUserVo> loginUsers = remoteUserService.getStaffs();
        return BeanUtil.copyToList(loginUsers, StaffVo.class);
    }

    @Override
    public List<JudgerVo> getJudgerList(Judger judger) {
        List<Judger> sysJudgerList = judgerMapper.selectList(judger);
        if (CollUtil.isEmpty(sysJudgerList)) {
            return new ArrayList<>();
        }
        // 属性拷贝
        List<JudgerVo> sysJudgerVoList = BeanUtil.copyToList(sysJudgerList, JudgerVo.class);
        for (JudgerVo judgerVO : sysJudgerVoList) {
            // 设置用户和判题数目
            List<String> nickNames = new ArrayList<>();
            Set<String> statusSet = new HashSet<>();
            int numberOfJudge = 0;
            // 获取当前判题人所有的答题用户
            List<Judger2Answerer> judger2AnswererList = judger2AnswererMapper.selectList(new Judger2Answerer(judgerVO.getUserId()));
            if (CollUtil.isNotEmpty(judger2AnswererList)) {
                for (Judger2Answerer judger2Answerer : judger2AnswererList) {
                    Long replyUserId = judger2Answerer.getReplyUserId();
                    RemoteUserVo remoteUserVo = remoteUserService.getUserById(replyUserId);
                    if (ObjectUtil.isNotNull(remoteUserVo)) {
                        nickNames.add(remoteUserVo.getNickName());
                    }
                    // 获取所有答题记录并设置判题状态
                    List<String> replyIds = remoteUserSolveService.getUserAnswerRecordIds(replyUserId);
                    if (CollUtil.isNotEmpty(replyIds)) {
                        for (String replyId : replyIds) {
                            // 判断各个题目是否已经判题完毕
                            RemoteUserSolveVo userSolveVO = remoteUserSolveService.getUserSolveById(replyId);
                            if (ObjectUtil.isNotNull(userSolveVO)) {
                                statusSet.add(userSolveVO.getStatus());
                            }
                            numberOfJudge++;
                        }
                    }
                }
            }
            String status = statusSet.size() == 1 && statusSet.contains(JudgeConstants.JUDGE_FINISH) ?
                    JudgeConstants.JUDGE_FINISH :
                    JudgeConstants.JUDGE_NOT_IN_PROGRESS;
            judgerVO.setStatus(status);
            judgerVO.setNickNames(nickNames);
            // 设置所需要的判题数量
            judgerVO.setCount(numberOfJudge);
        }
        return sysJudgerVoList;
    }


    @Override
    public Judger getJudgerByUserId(Long userId) {
        return judgerMapper.selectById(userId);
    }

    @Override
    public int allotNewcomer(List<Judger> judgerList) {
        for (Judger judger : judgerList) {
            judger.setUpdateTime(LocalDateTime.now());
            judger.setUpdateBy("系统分配");
        }
        return judgerMapper.updateJudgerBatch(judgerList);
    }

    @Override
    public int deleteJudgerById(String judgerId) {
        return judgerMapper.deleteJudgerById(judgerId);
    }


    @Override
    public int setJudger(Judger judger) {
        Long userId = judger.getUserId();
        // 判断用户存在
        RemoteUserVo remoteUserVo = remoteUserService.getUserById(userId);
        if (ObjectUtil.isNull(remoteUserVo)) {
            throw new BusinessException("用户不存在, 注册判题人失败");
        }
        // 判断是否已经是判题人
        Judger judgerFromDB = getJudgerByUserId(userId);
        if (ObjectUtil.isNotNull(judgerFromDB)) {
            throw new BusinessException("该用户已经为判题人, 请勿多次设置");
        }
        // 参数设置
        judger.setJudgerId(IdUtil.getSnowflakeNextIdStr());
        judger.setJudgerName(remoteUserVo.getNickName());

        // 异步发送邮件通知
        return judgerMapper.insert(judger);
    }
}
